package server;

import java.io.IOException;
import java.net.ServerSocket;
import java.net.Socket;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;

import tools.DaemonThreadFactory;

public class MathServer implements Runnable{
	
	// All tasks should live only while main server app is running
	private final ExecutorService executor = Executors.newCachedThreadPool(new DaemonThreadFactory());
	
	/**
	 * waits for connection and if one is got spawns new thread and gives task execution to it
	 */
	@Override public void run() {

		// no user interface was planned so far for the server
		// that is why we constantly set port number to 80
		final int httpd = 80;

        ServerSocket ssock = null;
		try {
			ssock = new ServerSocket(httpd);
		} catch (IOException e) {
			System.out.println("Server> Port is busy, please try again later.");
			e.printStackTrace();
		}

		// Count tasks, for no reason.
		int Tasks = 0;
        while (true) {

            Socket sock = null;
			try {
				sock = ssock.accept();
			} catch (IOException e) {
				e.printStackTrace();
			}

            System.out.printf("Server> Task %d connected%n", ++Tasks);

            executor.execute(new TaskConnection(sock));
        }		
	}

}
